import java.io.IOException;
import java.net.*;
import java.sql.SQLOutput;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String severIP;
    private int severPort;
    public UdpEchoClient(String ip,int port) throws SocketException {
        socket = new DatagramSocket();
        severIP = ip;
        severPort = port;
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            //1.先从控制台读取用户输入的字符串
            System.out.println("-> ");
            String request = scanner.next();
            //2.把这个用户输入的内容，构造成一个UDP请求，并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(severIP),severPort);
            socket.send(requestPacket);
            //3.从服务器读取响应数据并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);
            String response = new String(responsePacket.getData(),0,requestPacket.getLength(),"UTF-8");
            //4.把响应结果显示到控制台上
            System.out.printf("req: %s,resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",8080);
        client.start();
    }
}
